package com.imooc.luckymoney.controller;

import com.imooc.luckymoney.domain.Result;
import com.imooc.luckymoney.entity.Luckymoney;
import com.imooc.luckymoney.repository.LuckymoneyRepository;
import com.imooc.luckymoney.service.LuckymoneyService;
import com.imooc.luckymoney.util.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * Restful API接口设计
 * GET  /luckymoneys    获取红包列表
 * POST /luckymoneys    创建一个红包
 * GET  /luckymoneys/id 通过ID查询红包
 * PUT  /luckymoneys/id 通过ID更新红包
 */
@RestController
public class CrudController {
    @Autowired
    private LuckymoneyRepository repository;

    @Autowired
    private LuckymoneyService service;

    /**
     * 获取红包列表
     */
    @GetMapping("/luckymoneys")
    public List<Luckymoney> list() {
        return repository.findAll();
    }

    /**
     * 创建红包(发红包)
     * 使用@Valid进行表单校验，校验的结果会写入到BindingResult对象中。
     * 如果有多个@Valid注解，BindingResult对象的顺序需要紧随其后，与其一一对应
     * 在被校验的对象Luckymoney中，使用@Min、@NotNull等注解进行约束
     */
    @PostMapping("/luckymoneys")
    public Result<Luckymoney> create(@Valid Luckymoney luckymoney, BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            return ResultUtils.error(-1,bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultUtils.success(repository.save(luckymoney));
    }

    /**
     * 通过id查询红包
     */
    @GetMapping("/luckymoneys/{id}")
    public Luckymoney findById(@PathVariable("id") Integer id) {
        return repository.findById(id).orElse(null);
    }

    /**
     * 更新红包(领红包)
     * 查询是否存在这条数据，如存在再更新
     */
    @PutMapping("/luckymoneys/{id}")
    public Luckymoney update(@PathVariable("id") Integer id,
                             @RequestParam("consumer") String consumer) {
        Optional<Luckymoney> optional = repository.findById(id);
        if (optional.isPresent()) {
            Luckymoney luckymoney = optional.get();
            luckymoney.setConsumer(consumer);
            return repository.save(luckymoney);
        }
        return null;
    }

    @PostMapping("/luckymoneys/two")
    public void createTwo() {
        service.createTwo();
    }

    @GetMapping("/luckymoneys/getAmount/{id}")
    public void getAmount(@PathVariable("id") Integer id) throws Exception{

        service.getAmount(id);
    }
}
